<template>
  <div class="component-one">
    <div class="select-container">
      <el-select v-model="selectedCountry" placeholder="请选择国家" @change="handleCountryChange">
        <el-option
          v-for="item in countryOptions"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
    </div>

    <div class="chart-container" ref="chartContainer"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const selectedCountry = ref('')
const countryOptions = ref([])
const chartInstance = ref(null)
const chartContainer = ref(null)

// 获取国家列表
const fetchCountryList = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/select_list_region')
    if (response.data.success) {
      countryOptions.value = response.data.data
      // 设置默认选中第一个国家
      selectedCountry.value = response.data.data[0]
      // 获取默认国家的数据
      fetchChartData(selectedCountry.value)
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    console.error('获取国家列表失败：', error)
    ElMessage.error('获取国家列表失败')
  }
}

// 获取图表数据
const fetchChartData = async (country) => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/olympic_people', {
      params: {
        country: country
      }
    })

    if (response.data.success) {
      renderChart(response.data.data)
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    console.error('获取图表数据失败：', error)
    ElMessage.error('获取图表数据失败')
  }
}

// 渲染图表
const renderChart = (data) => {
  if (!chartInstance.value) {
    chartInstance.value = echarts.init(chartContainer.value)
  }

  const years = data.map(item => item.Year)
  const summerData = data.map(item => item.summer)
  const winterData = data.map(item => item.winter)

  const option = {
    title: {
      text: '参赛人员变化分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#E0E0E0',
      borderWidth: 1,
      padding: [8, 16],
      textStyle: {
        color: '#666',
        fontSize: 12
      },
      formatter: function(params) {
        const year = params.name
        const summer = summerData[params.dataIndex] || 0
        const winter = winterData[params.dataIndex] || 0
        return `<div style="font-size:14px; color:#333; margin-bottom:8px;">${year}</div>
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
                  <div style="display:flex; align-items:center;">
                    <span style="display:inline-block; width:8px; height:8px; border-radius:50%; background-color:#FF4B4B; margin-right:6px;"></span>
                    <span>夏季奥运会</span>
                  </div>
                  <span style="font-weight:500;">${summer}</span>
                </div>
                <div style="display:flex; justify-content:space-between; align-items:center;">
                  <div style="display:flex; align-items:center;">
                    <span style="display:inline-block; width:8px; height:8px; border-radius:50%; background-color:#87CEEB; margin-right:6px;"></span>
                    <span>冬季奥运会</span>
                  </div>
                  <span style="font-weight:500;">${winter}</span>
                </div>`
      }
    },
    legend: {
      data: ['夏季', '冬季'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: years,
      name: '年份'
    },
    yAxis: {
      type: 'value',
      name: '参赛人数'
    },
    series: [
      {
        name: '夏季',
        type: 'line',
        data: summerData,
        smooth: true,
        itemStyle: {
          color: '#FF4B4B' // 红色
        },
        lineStyle: {
          color: '#FF4B4B'
        }
      },
      {
        name: '冬季',
        type: 'line',
        data: winterData,
        smooth: true,
        itemStyle: {
          color: '#87CEEB' // 冰蓝色
        },
        lineStyle: {
          color: '#87CEEB'
        }
      }
    ]
  }

  chartInstance.value.setOption(option)
}

// 处理国家选择变化
const handleCountryChange = (value) => {
  fetchChartData(value)
}

// 监听窗口大小变化
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
}

onMounted(() => {
  fetchCountryList()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.component-one {
  padding: 20px;
}

.select-container {
  margin-bottom: 20px;
  text-align: left;
}

.chart-container {
  width: 100%;
  height: 500px;
}
</style>
